import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { combineLatest, forkJoin, withLatestFrom } from 'rxjs';
import { AlbumService } from 'src/app/service/apis/album.service';
import { Album, AlbumInfo, Anchor, Category, MetaData, MetaValue, SubCategory, TracksInfo } from 'src/app/service/apis/types';
import { CategoryService } from 'src/app/service/business/category.service';

export interface CategoryInfo {
  category: Category;
  currentSubcategory: SubCategory;
  subcategories: SubCategory[];
  metadata: MetaData[];
}

export interface AlbumsInfo {
  albums: Album[];
  page: number;
  pageSize: number;
  total: number;
  pageConfig: { h1title: string };
}

export interface AlbumArgs {
  category: string;
  subcategory: string;
  meta: string;
  sort: number;
  page: number;
  perPage: number;
}

export interface AlbumRes {
  albumId: number;
  mainInfo: AlbumInfo;
  anchorInfo: Anchor;
  tracksInfo: TracksInfo;
}

export interface AlbumTrackArgs {
  albumId: string;
  sort: number;
  pageNum: number;
  pageSize: number;
}

interface CheckedMeta {
  metaRowId: number;
  metaRowName: string;
  metaId: number;
  metaName: string;
}
@Component({
  selector: 'axz-albums',
  templateUrl: './albums.component.html',
  styleUrls: ['./albums.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class AlbumsComponent implements OnInit {

  searchParams: AlbumArgs = {
    category: '',
    subcategory: '',
    meta: '',
    sort: 0,
    page: 1,
    perPage: 30
  };
  categoryInfo?: CategoryInfo;
  sorts = ['综合排序', '最近更新', '播放最多'];
  readonly prefix = '/xmly/';
  item: any;
  albumsInfo?: AlbumsInfo;
  checkedMetas: CheckedMeta[] = [];
  constructor(private albumServe: AlbumService, private categoryServe: CategoryService, private ref: ChangeDetectorRef, private activerouter: ActivatedRoute, private router: Router) { }

  ngOnInit(): void {
    this.albumServe.albums(this.searchParams)
    // 监听路由参数变化
    this.activerouter.paramMap.pipe(withLatestFrom(this.categoryServe.getCategory()))
      .subscribe(([paramMap, category]) => {
        const pinyin: any = paramMap.get('albumId');
        console.log('pinyin', pinyin)
        if (pinyin !== category) {
          this.categoryServe.setCategory(pinyin);
        }
        this.searchParams.category = pinyin;
        this.searchParams.subcategory = '';
        this.categoryServe.setSubCategory([]);
        this.unCheckMeta('clear')
        this.updatePageDatas();
      });
  }


  /**
   * 二三级分类
   */
  updatePageDatas(): void {
    // 每个 Observable有返回值才会被订阅
    forkJoin([
      this.albumServe.albums(this.searchParams),
      this.albumServe.detailCategoryPageInfo(this.searchParams)
    ]).subscribe(([albumsInfo,categoryInfo])=>{
      console.log('albumsInfo',albumsInfo)
      this.albumsInfo=albumsInfo
      this.categoryInfo = categoryInfo;
      this.ref.markForCheck();
    })
  }


  /**
   * 二级分类点击事件
   */
  changeSubCategory(subcategory?: SubCategory) {
    if (this.searchParams.subcategory !== subcategory?.code) {
      this.searchParams.subcategory = subcategory?.code || '';
      console.log('subcategory', this.searchParams.subcategory);
      this.unCheckMeta('clear')
      this.updatePageDatas();
    }
  }

  /**
   * 点击三级菜单
   *
   * @param {MetaData} metaData
   * @param {MetaValue} metaValue
   * @memberof AlbumsComponent
   */
  changeMeta(metaData: MetaData, metaValue: MetaValue): void {
    this.checkedMetas.push({
      metaRowId: metaData.id,
      metaRowName: metaData.name,
      metaId: metaValue.id,
      metaName: metaValue.displayName
    });
    this.searchParams.meta = this.getMetaParam();
  }

  /**
   * 是否显示二级菜单
   *
   * @param {string} name
   * @return {*}  {boolean}
   * @memberof AlbumsComponent
   */
  showMetaRow(name: string): boolean {
    if (this.checkedMetas.length) {
      return this.checkedMetas.findIndex(item => item.metaRowName === name) === -1;
    }
    return true;
  }


  /**
   * 清除全部
   * 
   * @param {(CheckedMeta | 'clear')} meta
   * @memberof AlbumsComponent
   */
  unCheckMeta(meta: CheckedMeta | 'clear') {
    if (meta === 'clear') {
      this.checkedMetas = [];
    } else {
      const targetIndex = this.checkedMetas.findIndex(item => {
        return (item.metaRowId === meta.metaRowId) && (item.metaId === meta.metaId);
      });
      if (targetIndex > -1) {
        this.checkedMetas.splice(targetIndex, 1);
        this.searchParams.meta = this.getMetaParam();
      }
    }
    this.updateAlbums();
  }


  private getMetaParam(): string {
    let result = '';
    if (this.checkedMetas.length) {
      this.checkedMetas.forEach(item => {
        result += item.metaRowId + '_' + item.metaId + '-';
      });
    }
    return result.slice(0, -1);
  }


  /**
   * 排序
   * @param index 
   */
  changeSort(index: number): void {
    if (this.searchParams.sort !== index) {
      this.searchParams.sort = index;
      this.updateAlbums();
    }
  }


  private updateAlbums(): void {
    this.albumServe.albums(this.searchParams).subscribe(albumsInfo => {
      this.albumsInfo = albumsInfo;
      this.ref.markForCheck();
    });
  }

  trackByAlbums(index: number, item: Album): number { return item.albumId; }
}
